package kr.co.hk.fac;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import kr.co.hk.R;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class FacList extends Activity {

	private ListView listView;
	private ArrayList<FacInfo> arrayList;
	private ArrayAdapter<FacInfo> arrayAdapter;
	private String totCnt = "0";
	private String pageIndex = "";
	private String group = "";
	private String facName = "";
	private String seq = "";
	private String htmlurl;
	private int maxPageNo = 1;
	private ProgressDialog progressDialog;
	final private int PROGRESS_DIALOG = 0;
	private boolean pageEx = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fac_list);

		listView = (ListView) findViewById(R.id.facList);

		arrayList = new ArrayList<FacInfo>();
	
		arrayAdapter = new ArrayAdapter<FacInfo>(this,
				android.R.layout.simple_list_item_1, arrayList);
		listView.setAdapter(arrayAdapter);
		listView.setOnItemClickListener(itemclick);

		init();

		Button btnNext = (Button) findViewById(R.id.btnNext);
		btnNext.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				int nextInt = Integer.parseInt(pageIndex) + 1;
				if (maxPageNo < nextInt) {
					toast("마지막 페이지 입니다.");
				} else {
					threadStart(htmlurl + "&pageIndex=" + nextInt);
				}

			}
		});

		Button btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				int backInt = Integer.parseInt(pageIndex) - 1;
				if (1 > backInt) {
					toast("첫 페이지 입니다.");
				} else {
					threadStart(htmlurl + "&pageIndex=" + backInt);
				}
			}
		});
	}

	private void threadStart(final String html) {
		pageEx = false;
		showDialog(PROGRESS_DIALOG);
		listClear();
		new Thread() {
			public void run() {
				getFacfList(html);
				
				Message msg = handler.obtainMessage();
				handler.sendMessage(msg);
			}
		}.start();
	}

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			FacList.this.removeDialog(PROGRESS_DIALOG);
			if(pageEx){
				excePro();
			}else{
				arrayAdapter.notifyDataSetChanged();
				if (totCnt.equals("") || totCnt.equals("0") || totCnt.equals(null)) {
					toast("검색된 목록이 없습니다.");
					onBackPressed();
				}
			}
			
			

		}
	};

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_DIALOG:

			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Now loading..");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(false);
			return progressDialog;

		}
		return null;

	}

	private void init() {
		Bundle extra = getIntent().getExtras();
		int groupNum = extra.getInt("groupNum");
		int localNum = extra.getInt("localNum");

		String searchKeyword = extra.getString("searchKeyword");

		Resources r = getResources();
		int[] facCodeArr = r.getIntArray(R.array.searchFacCl_code);
		String[] localArr = r.getStringArray(R.array.searchLocal);

		String searchFacCl = facCodeArr[groupNum] + "";
		String searchLocal = localArr[localNum] + "";

		if (searchKeyword != null) {
			searchFacCl = "";
			searchLocal = "";
		} else {
			searchKeyword = "";
		}

		String encodedLocal = "";
		String encodedKeyword = "";
		try {
			encodedLocal = URLEncoder.encode(searchLocal, "utf-8");
			encodedKeyword = URLEncoder.encode(searchKeyword, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		htmlurl = "http://www.women.go.kr/new_women/women/info/fac/selectFacList.do?"

				+ "searchFacCl="
				+ searchFacCl
				+ "&searchKeyword="
				+ encodedKeyword + "&searchLocal=" + encodedLocal;

		threadStart(htmlurl);

	}

	public void getFacfList(String addr) {
		try {

			URL url = new URL(addr);
			System.out.println(addr);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			if (conn != null) {

				conn.setConnectTimeout(10000);
				conn.setReadTimeout(10000);
				conn.setUseCaches(false);

				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

					BufferedReader br = new BufferedReader(
							new InputStreamReader(conn.getInputStream(),
									"utf-8"));
					ArrayList<String> list = new ArrayList<String>();
					String msg = "";
					while ((msg = br.readLine()) != null) {
						list.add(msg.trim() + "\n");
					}

					for (int i = 0; i < list.size(); i++) {

						boolean isChk = false;
						String line = list.get(i);

						String reStr = line;
						int firstIndex = 0;
						int lastIndex = 0;

						if (line.contains("id=\"totCnt")) {
							firstIndex = reStr.indexOf("value=");
							lastIndex = reStr.indexOf("\" />");
							totCnt = reStr.substring(firstIndex + 7, lastIndex);
						
							maxPageNo = Integer.parseInt(totCnt) / 10;
							if (Integer.parseInt(totCnt) % 10 > 0) {
								maxPageNo += 1;
							}

						}
						if (line.contains("id=\"pageIndex")) {
							firstIndex = reStr.indexOf("value=");
							lastIndex = reStr.indexOf("\"/>");
							pageIndex = reStr.substring(firstIndex + 7,
									lastIndex);
						}
						if (line.contains("class=\"category")) {

							firstIndex = reStr.indexOf("\">");
							lastIndex = reStr.indexOf("</td>");
							group = reStr.substring(firstIndex + 2, lastIndex);
						
						}

						if (line.contains("javascript:fncGoView")) {
							
							firstIndex = reStr.indexOf(";\">");
							lastIndex = reStr.indexOf("</a></td>");
							facName = reStr
									.substring(firstIndex + 3, lastIndex);
							int fIndex = reStr.indexOf("(");
							int lIndex = reStr.indexOf(");");
							seq = reStr.substring(fIndex + 1, lIndex);
					
							
						
						}

						if (!group.equals("") && !facName.equals("")
								&& !seq.equals("")) {
							isChk = true;

						}

						if (isChk) {
							FacInfo facinfo = new FacInfo(facName, group, seq);

							arrayList.add(facinfo);
							
							seq = "";
							group = "";
							facName = "";
						}

					}

					br.close();
				}
				conn.disconnect();
			}
		} catch (Exception ex) {
			pageEx= true;
			ex.printStackTrace();
		}
	}

	AdapterView.OnItemClickListener itemclick = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int position,
				long id) {
			FacInfo facinfo = arrayList.get(position);
			Intent intent = new Intent(FacList.this, FacDetails.class);
			intent.putExtra("seq", facinfo.getSeq());

			startActivity(intent);

		}

	};

	private void listClear() {
		arrayList.clear();
		arrayAdapter.clear();
	}
	private void excePro(){
		toast("페이지 로딩시 오류가  있습니다. \n 네트워크 확인 후 다시 시도 하세요!");
		onBackPressed();
	}
	private void toast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
}
